/**
 * WorthDoing.ai
 * Author: Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 * File: src/app/opportunity/[id]/page.tsx
 * Description: Opportunity report page — streamed report, scores with confidence, evidence, competitors, skeptic case.
 */
import Link from "next/link";
import { notFound } from "next/navigation";
import { and, asc, eq, inArray } from "drizzle-orm";
import { db } from "@/lib/db/client";
import {
  opportunities,
  opportunityScores,
  opportunityEvidence,
  opportunityCompetitors,
  competitors,
  evidence,
  sources,
  investigations,
} from "@/lib/db/schema";
import { Markdown } from "@/components/wd/Markdown";
import { ScorePanel } from "@/components/wd/ScorePanel";
import { WorthScore } from "@/components/wd/OpportunityCard";
import { EvidenceKindBadge } from "@/components/wd/badges";

export const dynamic = "force-dynamic";

export default async function OpportunityPage({ params }: PageProps<"/opportunity/[id]">) {
  const { id } = await params;
  if (!/^[0-9a-f-]{36}$/i.test(id)) notFound();

  const [opp] = await db.select().from(opportunities).where(eq(opportunities.id, id));
  if (!opp) notFound();

  const [inv] = await db.select().from(investigations).where(eq(investigations.id, opp.investigationId));
  const scores = await db.select().from(opportunityScores).where(eq(opportunityScores.opportunityId, id));
  const links = await db.select().from(opportunityEvidence).where(eq(opportunityEvidence.opportunityId, id));
  const evidenceIds = links.map((l) => l.evidenceId);
  const evRows = evidenceIds.length
    ? await db
        .select({
          id: evidence.id,
          kind: evidence.kind,
          quote: evidence.quote,
          summary: evidence.summary,
          strength: evidence.strength,
          sourceUrl: sources.canonicalUrl,
          sourceTitle: sources.title,
          sourceDomain: sources.domain,
        })
        .from(evidence)
        .innerJoin(sources, eq(sources.id, evidence.sourceId))
        .where(and(eq(evidence.investigationId, opp.investigationId), inArray(evidence.id, evidenceIds)))
        .orderBy(asc(evidence.createdAt))
    : [];
  const comps = await db
    .select({
      name: competitors.name,
      url: competitors.url,
      description: competitors.description,
      note: opportunityCompetitors.note,
    })
    .from(opportunityCompetitors)
    .innerJoin(competitors, eq(competitors.id, opportunityCompetitors.competitorId))
    .where(eq(opportunityCompetitors.opportunityId, id));

  return (
    <article className="mx-auto w-full max-w-4xl px-4 py-8 sm:px-6">
      {inv && (
        <Link
          href={`/investigate/${inv.id}`}
          className="font-mono text-[11px] uppercase tracking-wider text-tele hover:underline"
        >
          ← investigation: {inv.objective}
        </Link>
      )}

      <header className="mt-4 flex flex-col-reverse items-start justify-between gap-4 sm:flex-row">
        <div className="min-w-0">
          <h1 className="font-heading text-3xl font-semibold leading-tight tracking-tight text-ink sm:text-4xl">
            {opp.title}
          </h1>
          <p className="mt-3 max-w-2xl text-base leading-relaxed text-ink-soft">{opp.summary}</p>
        </div>
        <div className="shrink-0 rounded-xl border border-line bg-card px-5 py-4">
          <WorthScore score={opp.worthScore} confidence={opp.evidenceConfidence} size="lg" />
          <p className="mt-1 text-right font-mono text-[9px] uppercase tracking-widest text-ink-soft">
            worth score
          </p>
        </div>
      </header>

      <div className="mt-8 grid grid-cols-1 gap-6 lg:grid-cols-[1fr_320px]">
        <div className="min-w-0">
          {opp.reportMd ? (
            <Markdown>{opp.reportMd}</Markdown>
          ) : (
            <p className="rounded-xl border border-line bg-card p-6 font-mono text-sm text-ink-soft">
              The report has not been synthesized yet.
            </p>
          )}

          <section className="mt-10">
            <h2 className="mb-4 font-heading text-xl font-semibold text-ink">Evidence trail</h2>
            <ol className="space-y-3">
              {evRows.map((e, i) => (
                <li
                  key={e.id}
                  id={`evidence-${i + 1}`}
                  className="scroll-mt-24 rounded-xl border border-line bg-card p-4"
                >
                  <div className="flex items-center justify-between gap-2">
                    <span className="font-mono text-[11px] font-medium text-ink">[{i + 1}]</span>
                    <div className="flex items-center gap-2">
                      <EvidenceKindBadge kind={e.kind} />
                      <span className="font-mono text-[10px] text-ink-soft">
                        strength {Math.round(e.strength * 100)}%
                      </span>
                    </div>
                  </div>
                  <blockquote className="mt-2 border-l-2 border-line pl-3 text-sm italic leading-relaxed text-ink/85">
                    “{e.quote}”
                  </blockquote>
                  <p className="mt-2 text-[13px] text-ink-soft">{e.summary}</p>
                  <a
                    href={e.sourceUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="mt-2 inline-block truncate font-mono text-[11px] text-tele hover:underline"
                  >
                    {e.sourceTitle ?? e.sourceUrl} · {e.sourceDomain}
                  </a>
                </li>
              ))}
            </ol>
          </section>
        </div>

        <aside className="space-y-5">
          <section className="rounded-xl border border-line bg-card p-4">
            <h2 className="mb-4 font-mono text-[11px] uppercase tracking-widest text-ink-soft">
              Score breakdown
            </h2>
            <ScorePanel
              scores={scores.map((s) => ({
                dimension: s.dimension,
                score: s.score,
                confidence: s.confidence,
                reasoning: s.reasoning,
              }))}
            />
          </section>

          <section className="rounded-xl border border-signal/40 bg-signal/5 p-4">
            <h2 className="mb-2 font-mono text-[11px] uppercase tracking-widest text-signal">
              The skeptic’s case
            </h2>
            <p className="text-[13px] leading-relaxed text-ink/90">{opp.skepticCase}</p>
          </section>

          <section className="rounded-xl border border-rust/30 bg-rust/5 p-4">
            <h2 className="mb-2 font-mono text-[11px] uppercase tracking-widest text-rust">Risks</h2>
            <p className="text-[13px] leading-relaxed text-ink/90">{opp.risks}</p>
          </section>

          {comps.length > 0 && (
            <section className="rounded-xl border border-line bg-card p-4">
              <h2 className="mb-3 font-mono text-[11px] uppercase tracking-widest text-ink-soft">
                Competitive landscape
              </h2>
              <ul className="space-y-3">
                {comps.map((c) => (
                  <li key={c.name}>
                    {c.url ? (
                      <a
                        href={c.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-[13px] font-medium text-tele hover:underline"
                      >
                        {c.name}
                      </a>
                    ) : (
                      <span className="text-[13px] font-medium text-ink">{c.name}</span>
                    )}
                    <p className="mt-0.5 text-xs leading-relaxed text-ink-soft">
                      {c.description} {c.note && <span className="italic">— {c.note}</span>}
                    </p>
                  </li>
                ))}
              </ul>
            </section>
          )}
        </aside>
      </div>
    </article>
  );
}
